package ca.bcit.comp_3512.assignment_02.business_logic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

import ca.bcit.comp_3512.assignment_02.data_managers.WeeklyEntryManager;
import ca.bcit.comp_3512.assignment_02.data_models.WeeklyEntry;

@Named("editableWeeklyEntryList")
@SessionScoped
public class EditableWeeklyEntryList implements Serializable
{
    @Inject private WeeklyEntryManager weeklyEntryManager;
    List<EditableWeeklyEntry> weeklyEntryList;
    
    public List<EditableWeeklyEntry> getWeeklyEntryList()
    {
        if (weeklyEntryList == null) {
            refreshList();
        }
        return weeklyEntryList;
    }
    
    public void refreshList()
    {
        WeeklyEntry[] weeklyEntries = weeklyEntryManager.getAll();
        weeklyEntryList = new ArrayList<EditableWeeklyEntry>();
        for (int i = 0; i < weeklyEntries.length; ++i)
        {
            weeklyEntryList.add(new EditableWeeklyEntry(weeklyEntries[i]));
        }  
    }
    
    public  void setWeeklyEntryList(List<EditableWeeklyEntry> weeklyEntries)
    {
        weeklyEntryList = weeklyEntries;
    }
    
    public String deleteRow(EditableWeeklyEntry weeklyEntry)
    {
        weeklyEntryManager.remove(weeklyEntry.getWeeklyEntry());
        weeklyEntryList.remove(weeklyEntry);
        return null;
    }
    
    public String saveAll()
    {
        for (EditableWeeklyEntry weeklyEntry : weeklyEntryList)
        {
            if (weeklyEntry.isEditable())
            {
                weeklyEntryManager.merge(weeklyEntry.getWeeklyEntry());
                weeklyEntry.setEditable(false);
            }
        }
        return null;
    }
    
    public String save(EditableWeeklyEntry weeklyEntry)
    {
        weeklyEntryManager.merge(weeklyEntry.getWeeklyEntry());
        weeklyEntry.setEditable(false);
        return null;
    }
    
    public String edit(EditableWeeklyEntry weeklyEntry)
    {
        weeklyEntry.setEditable(!weeklyEntry.isEditable());
        return "schedule?faces-redirect=true";
    }
}
